import { Card, Table } from "antd";
import { DownOutlined, RightOutlined } from "@ant-design/icons";
import { getOneInfo } from "@/api/cmn";
import { OneList, OneItem } from "@/api/cmn/dict/types";
import { useEffect, useState } from "react";

export default function Dict() {
  const [list, setList] = useState<OneList>([]);

  const getOneInfoFun = async (id: number) => {
    const res = await getOneInfo(id);
    res.map((item) => {
      if (item.hasChildren) {
        item.children = [];
      }
      return item;
    });
    return res;
  };

  useEffect(() => {
    (async () => {
      const res = await getOneInfoFun(1);
      setList(res);
    })();
  }, []);

  const data: OneItem[] = list;

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
    },
    {
      title: "编码",
      dataIndex: "dictCode",
    },
    {
      title: "值",
      dataIndex: "id",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
  ];

  const expand = async (onExpand: any, record: any, e: any) => {
    const res = await getOneInfoFun(record.id);
    record.children = res;
    setList(list);
    onExpand(record, e);
  };

  return (
    <>
      <Card>
        <Table
          rowKey={"id"}
          dataSource={data}
          columns={columns}
          bordered
          pagination={false}
          expandIcon={({ expanded, onExpand, record }) => {
            if (record.hasChildren && expanded) {
              return <DownOutlined onClick={(e) => onExpand(record, e)} />;
            } else if (record.hasChildren && !expanded) {
              return (
                <RightOutlined
                  onClick={(e) => {
                    expand(onExpand, record, e);
                  }}
                />
              );
            } else {
              return <></>;
            }
          }}
        />
      </Card>
    </>
  );
}
